<?php

/**
 * Ajax_WebService.phtml - Webservice pour le front office
 *
 * @package
 * @author Alexis Eric
 * @copyright Copyright (c) 2012 - Erra Prod
 * @version $1.0$
 * @access public
 */
session_start();

/*
 * displaySmallPrestationFromId() - Affichage d'une prestation
 */

function displaySmallPrestationFromId($id, $uniqid, $close = true) {
    $res = '';
    if (is_numeric($id)) {
        $prestation = Msa_PrestationObject::getPrestationFromId($id);
        $res .= '<div class="prestation prestation-small" data-uniqid="' . $uniqid . '" data-presta-id="' . $id . '">';
        $name = strlen($prestation->internet_name) ? $prestation->internet_name : $prestation->prestation_name;
        $res .= '<span class="title">' . $name . '</span>';
        $res .= '&nbsp;&nbsp;&nbsp;|';
        if (Config_GeneralConfigObject::get('display_price') == 1 && $prestation->display_price == 1) {
            if (strlen($prestation->prix)) {
                $res .= '       <span class="prix">&nbsp;&nbsp;&nbsp;' . $prestation->prix . ' €</span>';
            }
        }
        if ($close == true) {
            $res .= '<span class="close-presta pointer">&nbsp;</span>';
        }
        $res .= '</div>';
    }
    return $res;
}

/**
 * timeMatch() - Retourne TRUE si la prestation à $time de durée $duration peut être inserée dans $openSlotcontainer
 * 
 * @param type $time
 * @param type $duration
 * @param type $openSlotContainer
 * @return boolean
 */
function timeMatch($time, $duration, $openSlotContainer) {
    $match = false;
    if (is_array($openSlotContainer)) {
        foreach ($openSlotContainer as $agenda_id => $slots) {
            if (is_array($slots)) {
                foreach ($slots as $slot) {
                    $start = $slot['start'];
                    $end = $slot['end'];
                    if (Tools_CalendarObject::is_between($time, $start, $end, $duration)) {
                        $match = true;
                    }
                }
            }
        }
    }
    return $match;
}

/**
 * displayCalendar() - Affichage du calendrier des disponibilités
 * @param type $dateTime
 * @param type $eventsData
 * @param type $forceAgenda
 * @return string
 */
function displayCalendar($dateTime, $eventsData, $forceAgenda = null) {
    $dayListFr = array(0 => 'Lundi', 1 => 'Mardi', 2 => 'Mercredi', 3 => 'Jeudi', 4 => 'Vendredi', 5 => 'Samedi', 6 => 'Dimanche');
    $monthListFr = array(1 => 'Jan', 2 => 'Fév', 3 => 'Mar', 4 => 'Avr', 5 => 'Mai', 6 => 'Juin', 7 => 'Juil', 8 => 'Août', 9 => 'Sept', 10 => 'Oct', 11 => 'Nov', 12 => 'Déc');
    $monthListLongFr = array(1 => 'Janvier', 2 => 'Février', 3 => 'Mars', 4 => 'Avril', 5 => 'Mai', 6 => 'Juin', 7 => 'Juillet', 8 => 'Août', 9 => 'Septembre', 10 => 'Octobre', 11 => 'Novembre', 12 => 'Décembre');

    $shop_id = $eventsData[0]['shop_id'];
    $prestation_id_list = array();
    foreach ($eventsData as $event) {
        $prestation_id_list[] = $event['prestation_id'];
    }
    $startWeek = strtotime(date('o-\\WW', $dateTime));
    $endWeek = $startWeek + (3600 * 24 * 7);
    $thisMonday = strtotime(date('o-\\WW', $dateTime));

    // Affichage de la liste des agendas
    ////////////////////////////////////
    $query = 'SELECT back_agenda_prestation.agenda_id as agenda_id, nom_agenda, nom_internet FROM msa_agendaobject, back_agenda_prestation  WHERE msa_agendaobject.disponible_sur_internet=1  AND msa_agendaobject.location=' . $shop_id . '  AND back_agenda_prestation.agenda_id=msa_agendaobject.id  AND back_agenda_prestation.prestation_id IN(' . implode(',', $prestation_id_list) . ');';
    $selectedAgendas = Erra_Core_DatabasePdo::SELECT($query);

    if (Erra_Core_DatabasePdo::rowCount()) {
        $agendas = array();
        $agendaAssociative = array('-' => 'Peu importe');
        while ($row = $selectedAgendas->fetch()) {
            $agendas[] = $row->agenda_id;
            $agendaAssociative[$row->agenda_id] = strlen($row->nom_internet) ? $row->nom_internet : $row->nom_agenda;
        }
    }
    // Forcer le calcul à partir de certains agendas
    if (is_numeric($forceAgenda)) {
        $agendas = array($forceAgenda);
    }

    $res = '';
    $result = Msa_LocationObject::getFullArray($shop_id);

    if (count($result) && count($result) == 1) {
        $shop = $result[0];
        $res .= '<div class="menu-container">';
        $res .= '   <span class="menu-item">';
        $res .= '       <a href="#reserver/' . $shop->id . '/' . Erra_Utils_Tools::toUrlCompliant($shop->nom) . '" id="category_selected">Catégories</a> >> Sélectionnez l\'heure du rendez vous';
        $res .= '   </span>';
        if (Config_GeneralConfigObject::get('choose_presta_on_calendar') == 1 && count($agendaAssociative)) {
            $res .= '   <span class="menu-item menu-item-right">';
            $res .= Erra_Fields_ComboBox::create('select_agenda_calendar')
                    ->setDescription('Choisissez un agenda')
                    ->fill($agendaAssociative)
                    ->addAttribute('data-time', $dateTime)
                    ->setValue($forceAgenda)
                    ->edit();
            $res .= '   </span>';
            $res .= '</div>';
        }
        $res .= '<div class="calendar-header">';
        $res .= '   <div class="navigation-element" style="float:left; margin-left:20px;">';
        $res .= '       <a href="#choisir_date/' . time_to_hybrid_date($dateTime - (3600 * 24 * 7)) . '"><div class="prev_date">&nbsp;</div></a>';
        $res .= '   </div>';
        $res .= '<div class="navigation-element">';
        $res .= '<div style="display:inline-block; width:890px; text-align:center;">';
        $res .= 'Semaine du ' . date('j', $startWeek) . ' au ' . date('j', $endWeek - (3600 * 12)) . ' ' . $monthListLongFr[date('n', $endWeek - (3600 * 12))];
        $res .= '</div>';
        $res .= '</div>';
        $res .= '   <div class="navigation-element" style="float:right;  margin-right:20px;">';
        $res .= '       <a href="#choisir_date/' . time_to_hybrid_date($dateTime + (3600 * 24 * 7)) . '" class="navigation-link"><div class="next_date">&nbsp;</div></a>';
        $res .= '   </div>';
        $res .= '</div>';

        if (count($agendaAssociative)) {
            $res .= '<table class="calendar-table" cellpadding="0" cellspacing="0">';
            $res .= '<tr>';

            for ($day = 0; $day < 7; $day++) {
                // Inscription des headers
                $extraClass = (date('N', $dateTime) == ($day + 1) && $thisMonday == strtotime(date('o-\\WW', time()))) ? 'style="color:#2869B0; font-weight:bold;"' : '';
                $currenTimeStamp = $thisMonday + (3600 * 24) * $day;
                $res .= '<th ' . $extraClass . '>';
                $res .= $dayListFr[$day] . '<br/>';
                $res .= date('d', $currenTimeStamp) . ' ' . $monthListFr[date('n', $currenTimeStamp)] . ' ' . date('Y', $currenTimeStamp);
                $res .= '</th>';
            }
            $res .= '</tr>';
            // Calcul de la durée totale des prestations
            $totalTime = 0;
            foreach ($eventsData as $event) {
                $duree = Erra_Core_DatabasePdo::SELECT('SELECT duree FROM msa_prestationobject WHERE id=' . $event['prestation_id']);
                if (Erra_Core_DatabasePdo::rowCount()) {
                    $duree = $duree->fetch();
                    $totalTime += $duree->duree * 60;
                }
            }


            $openSlotsForDeintersect = Tools_CalendarObject::getOpenWebSlotsForDeintersect($agendas, $startWeek, $endWeek, $prestation_id_list);

            $busySlotsContainer = array();
            foreach ($agendas as $i => $agenda) {
                $busySlotsContainer[$agenda] = Tools_CalendarObject::getBusySlots($agenda, $startWeek, $endWeek);
            }
            $openSlotContainer = Tools_CalendarObject::slotsDeintersect($openSlotsForDeintersect, $busySlotsContainer, $totalTime);
            $intervalTime = Config_GeneralConfigObject::get('duree_intervalle') * 60;
            $calendarTimes = Tools_CalendarObject::getOpeningAndClosureTime($startWeek, $intervalTime, $totalTime, $openSlotContainer);

            $openingTime = $calendarTimes['opening'];
            $closureTime = $calendarTimes['closure'];
            $decay = $closureTime - $openingTime;
            $hourInterval = array();
            for ($i = 0; $i <= $decay / $intervalTime; $i++) {
                $hourInterval[] = time_to_str_hour($openingTime + ($i * $intervalTime));
                $timeInterval[] = $openingTime + ($i * $intervalTime);
            }
            for ($i = 0; $i < count($hourInterval); $i++) {
                $res .= '<tr>';
                for ($day = 0; $day < 7; $day++) {
                    $prestationStart = $startWeek + (3600 * 24 * $day) + $timeInterval[$i];
                    $timeStr = (time() < $prestationStart && timeMatch($prestationStart, $totalTime, $openSlotContainer)) ? $hourInterval[$i] : '-';

                    $matchList = Tools_CalendarObject::getAgendaMatch($prestationStart, $totalTime, $openSlotContainer);
                    $timestampStr = ($timeStr == '-') ? '' : $prestationStart;
                    $class = ($timeStr == '-') ? '' : 'class="book_this pointer"';
                    $res .= '<td data-agenda-match="' . $matchList . '" data-resa-timestamp="' . $timestampStr . '" ' . $class . '>' . $timeStr . '</td>';
                }
                $res .= '</tr>';
            }
            $res .= '</table>';
        } else {
            $res .= '<center><br/><h2>Aucune disponibilité</h2></center>';
        }
    }
    return $res;
}

/**
 * get_paypal_infos - Retourne les informations du compte paypal
 */
if (isset($_POST['query']) && $_POST['query'] == 'get_paypal_infos') {
    $paypal_vendor_id = Config_GeneralConfigObject::get('paypal_vendor_id');
    $paypal_mode = Config_GeneralConfigObject::get('paypal_mode');

    echo json_encode(array('paypal_vendor_id' => $paypal_vendor_id, 'paypal_mode' => $paypal_mode));
}

/**
 * check_cart_compatible - Vérifie si un panier est compatible avec une boutique
 */
if (isset($_POST['query']) && $_POST['query'] == 'check_cart_compatible') {
    if (isset($_POST['shopping_session']) && is_array($_POST['shopping_session']) && is_numeric($_POST['target_shop'])) {
        $cartIsValid = true;
        $target_shop = $_POST['target_shop'];
        foreach ($_POST['shopping_session'] as $item) {
            // Check if this prestation exists in target shop
            $prestaExists = Erra_Core_DatabasePdo::SELECT('SELECT DISTINCT msa_agendaobject.id AS agenda_id FROM msa_agendaobject, back_agenda_prestation WHERE msa_agendaobject.id=back_agenda_prestation.agenda_id AND back_agenda_prestation.prestation_id=' . $item['prestation_id'] . ' AND msa_agendaobject.location=' . $target_shop);
            if (!Erra_Core_DatabasePdo::rowCount()) {
                $cartIsValid = false;
            }
        }
        if ($cartIsValid == true) {
            echo Erra_Utils_Rest::Code_200_OK(' ');
        } else {
            echo Erra_Utils_Rest::Code_401_Unauthorized("Certaines prestations ne sont pas proposées dans ce lieu. Merci d'en choisir un autre");
        }
    } else {
        echo Erra_Utils_Rest::Code_401_Unauthorized("Une erreur est survenue");
    }
}

/*
 * liste_boutiques - Liste les boutiques
 */
if (isset($_POST['query']) && $_POST['query'] == 'liste_boutiques') {
    $result = Msa_LocationObject::getFullArray();
    if (count($result)) {
        if (is_array($result)) {
            $res = '';
            $res .= '<div class="choose-shop">Choisissez le lieu où vous souhaitez prendre rendez-vous :</div>';
            $aClosure = false;
            foreach ($result as $i => $shop) {
                if (!($i % 3)) {
                    $res .= '<table class="choose-shop-table">';
                    $res .= '<tr>';
                }
                $res .= '<td>';
                $res .= '<div class="shop_class">';
                $res .= '   <div class="first-infos">';
                $res .= '       <a href="#boutique/' . $shop->id . '/' . Erra_Utils_Tools::toUrlCompliant($shop->nom) . '">';
                $res .= '           <div class="shop_name">' . $shop->nom . '</div>';
                if (strlen($shop->adresse)) {
                    $res .= '               <div class="shop_address">' . $shop->adresse . '</div>';
                } else {
                    $res .= '<br/>';
                }
                if (strlen($shop->ville_cp)) {
                    $res .= '           <div class="shop_ville_cp">' . $shop->ville_cp . '</div>';
                } else {
                    $res .= '<br/>';
                }
                if (strlen($shop->acces)) {
                    $res .= '           <div class="shop_ville_cp">Accès : ' . $shop->acces . '</div>';
                }
                if (strlen($shop->telephone)) {
                    $res .= '           <div class="shop_telephone">Tèl : ' . $shop->telephone . '</div>';
                } else {
                    $res .= '<br/>';
                }
                if (strlen($shop->infos_complementaires)) {
                    $res .= '          <br/> <div class="shop_infos_complementaires"><b><i>' . nl2br($shop->infos_complementaires) . '</i></b></div>';
                }
                $res .= '   </a>';
                $res .= '   <div class="toggle-more-infos pointer"><img src="images/ic-informations.png"/> Plus d\'informations</div>';
                $res .= '   </div>';
                $res .= '   <div class="more-infos">';
                $res .= '       <div class="shop_image">';
                if (strlen($shop->image) && stristr($shop->image, '.jpg') || stristr($shop->image, '.png') || stristr($shop->image, '.gif')) {
                    $res .= '       <img src="' . $shop->image . '" />';
                } else {
                    $res .= '       <img src="images/no-image.png" />';
                }
                $res .= '       </div>';
                $res .= '       <div class="shop_description">' . nl2br($shop->magasin_description) . '</div>';
                $res .= '   </div>';
                $res .= '</div>';

                $res .= '</td>';
                if (!($i + 1 % 3)) {
                    $res .= '</tr>';
                    $res .= '</table>';
                    $aClosure = true;
                }
            }
            if (!$aClosure) {
                $res .= '</tr>';
                $res .= '</table>';
            }
        }
        echo $res;
    } else {
        echo Erra_Utils_Rest::Code_204_No_Content('Aucune boutique disponible pour la reservation');
    }
}

/**
 * shop_infos - Informations sur une boutique
 */
if (isset($_POST['query']) && $_POST['query'] == 'shop_infos') {
    if (isset($_POST['id']) && is_numeric($_POST['id'])) {
        $result = Msa_LocationObject::getFullArray($_POST['id']);
        if (count($result) && count($result) == 1) {
            $shop = $result[0];
            $res = '';
            $res .= '<div class="resa_back">';
            $res .= '   <a href="#">Retour vers la sélection du lieu</a>';
            // Combobox location
            $location = Erra_Core_DatabasePdo::SELECT('SELECT id, nom FROM msa_locationobject');
            if (Erra_Core_DatabasePdo::rowCount()) {
                $locationArray = array();
                while ($row = $location->fetch()) {
                    $locationArray[$row->id] = $row->nom;
                }
                if (count($locationArray) > 1) {
                    // Display location combobox
                    $locationComboBox = Erra_Fields_ComboBox::create('switch_location')
                            ->setDescription("Changer d'établissement")
                            ->fill($locationArray)
                            ->addAttribute('class', 'switch_location')
                            ->setValue($shop->id);
                    $res .= $locationComboBox->edit();
                }
            }
            $res .= '</div>';
            $res .= '<br/>';
            $res .= '<div class="shop_class_selected">';
            $res .= '   <div class="shop_image">';
            $res .= '       <a href="#boutique-' . $shop->id . '-' . Erra_Utils_Tools::toUrlCompliant($shop->nom) . '">';
            if (strlen($shop->image) && stristr($shop->image, '.jpg') || stristr($shop->image, '.png') || stristr($shop->image, '.gif')) {
                $res .= '       <img src="' . $shop->image . '" />';
            } else {
                $res .= '       <img src="images/no-image.png" />';
            }
            $res .= '       </a>';
            $res .= '   </div>';
            $res .= '   <div class="selected_shop_detail">';
            $res .= '           <div class="shop_name">' . $shop->nom . '</div>';
            if (strlen($shop->adresse)) {
                $res .= '               <div class="shop_address">' . $shop->adresse . '</div>';
            } else {
                $res .= '<br/>';
            }
            if (strlen($shop->ville_cp)) {
                $res .= '           <div class="shop_ville_cp">' . $shop->ville_cp . '</div>';
            } else {
                $res .= '<br/>';
            }
            if (strlen($shop->telephone)) {
                $res .= '           <div class="shop_telephone">Tèl : ' . $shop->telephone . '</div>';
            } else {
                $res .= '<br/>';
            }
            $res .= '       </div>';
            $res .= '</div>';
            $res .= '<div class="resa_class">';
            $res .= '   <a href="#reserver/' . $shop->id . '/' . Erra_Utils_Tools::toUrlCompliant($shop->nom) . '">';
            $res .= '<button type="button" name="" value="" class="book_now blue_button pointer">Réserver maintenant</button>';
            $res .= '   </a>';
            $res .= '</div>';
            echo $res;
        } else {
            echo Erra_Utils_Rest::Code_204_No_Content('Aucune information disponible pour ce lieu');
        }
    } else {
        echo Erra_Utils_Rest::Code_400_Bad_Request('La requête est erronée');
    }
}

/**
 * shop_detail - Affiche les détails sur une boutique
 */
if (isset($_POST['query']) && $_POST['query'] == 'shop_detail') {
    if (isset($_POST['id']) && is_numeric($_POST['id'])) {
        $result = Msa_LocationObject::getFullArray($_POST['id']);
        if (count($result) && count($result) == 1) {
            $res = '';
            $shop = $result[0];
            $res .= '<div class="tabs">';
            $res .= '   <ul>';
            $res .= '       <li><a href="#plan">Plan d\'accès</a></li>';
            $res .= '       <li><a href="#fiche">Informations sur la réservation</a></li>';
            $res .= '   </ul>';
            $res .= '   <div id="plan">';
            $res .= '       <div id="map_canvas" style="height:300px; width:600px"></div>';
            $res .= '       <script type="text/javascript">';
            $res .= 'initializeMap("' . $shop->adresse . ' ' . $shop->ville_cp . '");';
            $res .= '</script>';
            $res .= '   </div>';
            $res .= '   <div id="fiche">';
            $res .= 'Réservation en ligne 24H/24 7J/7<br/>
                     Vous pouvez prendre rendez-vous par Internet en activant votre compte de réservation en ligne.<br/>
                     Si vous ne recevez pas d\'e-mail d\'activation de compte de prise de RDV, pensez à vérifier vos courriers indésirables ou spam.';
            $res .= '   </div>';
            $res .= '</div>';
            echo $res;
        } else {
            echo Erra_Utils_Rest::Code_204_No_Content('Aucune information disponible pour ce lieu');
        }
    } else {
        echo Erra_Utils_Rest::Code_400_Bad_Request('La requête est erronée');
    }
}

/**
 * reserver - Reserver une prestation
 */
if (isset($_POST['query']) && $_POST['query'] == 'reserver') {
    if (isset($_POST['id']) && is_numeric($_POST['id'])) {
        $result = Msa_LocationObject::getFullArray($_POST['id']);
        if (count($result) && count($result) == 1) {
            $shop = $result[0];
            // Get all prestation types
            $location_id = $_POST['id'];
            $related_agendas = Erra_Core_DatabasePdo::SELECT('SELECT id FROM msa_agendaobject WHERE disponible_sur_internet=1 AND location=' . $location_id);
            $res = '';
            if (Erra_Core_DatabasePdo::rowCount()) {
                $relatedAgendasId = array();
                while ($row = $related_agendas->fetch()) {
                    $relatedAgendasId[] = $row->id;
                }
                // Now find all prestations types related to this/these agenda(s)
                $relatedPrestationTypes = Msa_TypeprestationObject::getPrestationTypesFromAgendaId($relatedAgendasId);
                if (count($relatedPrestationTypes) > 1) {
                    $res .= '<div class="menu-container">';
                    $res .= '<span class="menu-item">';
                    $res .= 'Catégories';
                    $res .= '</span>';
                    $res .= '</div>';
                    foreach ($relatedPrestationTypes as $prestationType) {
                        if ($prestationType->enabled == 1) {
                            $res .= '<div class="prestation_type">';
                            $res .= '   <a href="#liste_prestations/' . $shop->id . '/' . $prestationType->id . '/' . Erra_Utils_Tools::toUrlCompliant($prestationType->prestation_type_name) . '">';
                            $res .= '<div class="title">' . $prestationType->prestation_type_name . '</div>';
                            if (strlen($prestationType->image_type_prestation)) {
                                $res .= '   <div class="prestation_image"><img src="' . config_get('public_upload_directory') . '/' . $prestationType->image_type_prestation . '" /></div>';
                            } else {
                                $res .= '   <div class="prestation_image"><img src="images/no-image.png" /></div>';
                            }
                            $res .= strip_tags($prestationType->description_prestation, '<b><i><sup><sub><em><strong><u><br>');
                            $res .= '</a>';
                            $res .= '</div>';
                        }
                    }
                } else {
                    // Try fetching directly prestations
                    $res = '<div class="menu-container">';
                    $res .= '<span class="menu-item">';
                    $res .= 'Prestations';
                    $res .= '</span>';
                    $res .= '</div>';
                    $prestations = Msa_PrestationObject::getPrestationListFromShopId($_POST['id']);
                    if (is_array($prestations)) {
                        foreach ($prestations as $prestation) {
                            $res .= '<div class="prestation_type">';
                            $name = strlen($prestation->internet_name) ? $prestation->internet_name : $prestation->prestation_name;

                            $res .= '   <a id="rdv-dialog-link" href="#reserver/' . $shop->id . '/' . $prestation->id . '">';
                            $res .= '   <div class="title">' . $name . '</div>';
                            if (strlen($prestation->image_prestation)) {
                                $res .= '   <div class="prestation_image"><img src="' . config_get('public_upload_directory') . '/' . $prestation->image_prestation . '" /></div>';
                            } else {
                                $res .= '   <div class="prestation_image"><img src="images/no-image.png" /></div>';
                            }
                            $duree = minutes_to_str_hour($prestation->duree);
                            $res .= '           <span class="duree">' . $duree . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>';
                            if (Config_GeneralConfigObject::get('display_price') == 1 && $prestation->display_price == 1) {
                                if (strlen($prestation->prix)) {
                                    $res .= '       <span class="prix">' . $prestation->prix . ' €</span>';
                                }
                            }
                            $res .= '   </a>';
                            $shortDesc = (strlen($prestation->description_courte_prestation) > 125) ? substr($prestation->description_prestation, 0, 125) . '...' : '';
                            $res .= '   <div class="description">' . strip_tags($shortDesc, '<b><i><sup><sub><em><strong><u><br>') . '</div>';
                            $res .= '</div>';
                        }
                    }
                }
            }
            echo $res;
        } else {
            echo Erra_Utils_Rest::Code_204_No_Content('Contenu indisponible');
        }
    } else {
        echo Erra_Utils_Rest::Code_400_Bad_Request('Erreur dans la requête [' . __LINE__ . ']');
    }
}

/**
 * liste_prestations - Liste des prestations
 */
if (isset($_POST['query']) && $_POST['query'] == 'liste_prestations') {
    if (isset($_POST['shop_id']) && is_numeric($_POST['shop_id'])) {
        if (isset($_POST['presta_type_id']) && is_numeric($_POST['presta_type_id'])) {
            $result = Msa_LocationObject::getFullArray($_POST['shop_id']);
            if (count($result) && count($result) == 1) {
                $shop = $result[0];
// List of prestations
                $res = '';
                $type_prestation = Erra_Core_DatabasePdo::SELECT('SELECT prestation_type_name FROM msa_typeprestationobject WHERE id=' . $_POST['presta_type_id'])->fetch();
                $type_prestation = $type_prestation->prestation_type_name;


                $res .= '<div class="menu-container">';
                $res .= '<span class="menu-item">';
                $res .= '<a href="#reserver/' . $shop->id . '/' . Erra_Utils_Tools::toUrlCompliant($shop->nom) . '" id="category_selected">Catégories</a> >> ' . $type_prestation;
                $res .= '</span>';
                $res .= '</div>';
                $prestations = Msa_PrestationObject::getPrestationListFromShopIdAndTypeId($_POST['shop_id'], $_POST['presta_type_id']);
                if (is_array($prestations)) {
                    foreach ($prestations as $prestation) {
                        $res .= '<div class="prestation_type">';
                        $name = strlen($prestation->internet_name) ? $prestation->internet_name : $prestation->prestation_name;

                        $res .= '   <a id="rdv-dialog-link" href="#reserver/' . $shop->id . '/' . $prestation->id . '">';
                        $res .= '<div class="title">' . $name . '</div>';
                        if (strlen($prestation->image_prestation)) {
                            $res .= '   <div class="prestation_image"><img src="' . config_get('public_upload_directory') . '/' . $prestation->image_prestation . '" /></div>';
                        } else {
                            $res .= '   <div class="prestation_image"><img src="images/no-image.png" /></div>';
                        }
                        $duree = minutes_to_str_hour($prestation->duree);
                        $res .= '<span class="duree">' . $duree . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>';
                        if (Config_GeneralConfigObject::get('display_price') == 1 && $prestation->display_price == 1) {
                            if (strlen($prestation->prix)) {
                                $res .= '       <span class="prix">' . $prestation->prix . ' €</span>';
                            }
                        }
                        $res .= '</a>';

                        $shortDesc = (strlen($prestation->description_courte_prestation) > 125) ? substr($prestation->description_prestation, 0, 125) . '...' : '';
                        $res .= '   <div class="description">' . strip_tags($shortDesc, '<b><i><sup><sub><em><strong><u><br>') . '</div>';
                        $res .= '</div>';
                    }
                    echo $res;
                } else {
                    echoErra_Utils_Rest::Code_204_No_Content('Aucune prestation à afficher');
                }
            } else {
                echo Erra_Utils_Rest::Code_400_Bad_Request('Erreur dans la requête [' . __LINE__ . ']');
            }
        } else {
            echo Erra_Utils_Rest::Code_400_Bad_Request('Erreur dans la requête [' . __LINE__ . ']');
        }
    }
}

/**
 * presta_detail - Affiche les détails d'une prestation
 */
if (isset($_POST['query']) && $_POST['query'] == 'presta_detail') {
    if (isset($_POST['shop_id']) && is_numeric($_POST['shop_id'])) {
        if (isset($_POST['prestation_id']) && is_numeric($_POST['prestation_id'])) {
            $res = '';
            $prestation = Msa_PrestationObject::getPrestationFromId($_POST['prestation_id']);
            $res .= '<div class="prestation">';
            $res .= '   <div class="presta-left">';
            if (strlen($prestation->image_prestation)) {
                $res .= '   <div class="image_presta"><img src="' . config_get('public_upload_directory') . '/' . $prestation->image_prestation . '" /></div>';
            } else {
                $res .= '   <div class="image_presta"><img src="images/no-image.png" /></div>';
            }
            $res .= '   </div>';
            $res .= '   <div class="presta-right">';
            $name = strlen($prestation->internet_name) ? $prestation->internet_name : $prestation->prestation_name;
            $res .= '       <div class="title">' . $name . '</div>';
            $duree = minutes_to_str_hour($prestation->duree);
            $res .= '       <span class="duree"> ' . $duree . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>';
            if (Config_GeneralConfigObject::get('display_price') == 1 && $prestation->display_price == 1) {
                if (strlen($prestation->prix)) {
                    $res .= '       <span class="prix">' . $prestation->prix . ' €</span>';
                }
            }
            $res .= '       <div class="description">' . strip_tags($prestation->description_prestation, '<b><i><sup><sub><em><strong><u><br>') . '</div>';
            $res .= '   </div>';
            $res .= '</div>';
            echo $res;
        } else {
            echo Erra_Utils_Rest::Code_400_Bad_Request();
        }
    } else {
        echo Erra_Utils_Rest::Code_400_Bad_Request();
    }
}

/**
 * ajouter_presta - Ajouter une prestation
 */
if (isset($_POST['query']) && $_POST['query'] == 'ajouter_presta') {
    if (isset($_POST['rdv_data']) && is_array($_POST['rdv_data'])) {
        $res = '';
        // Obtenir les eventuelles prestations en session
        $prestations = $_POST['rdv_data'];
        if (is_array($prestations) && count($prestations)) {
            $res .= '<div class="cart-title">Vos réservations</div>';
            foreach ($prestations as $prestation) {
                $res .= displaySmallPrestationFromId($prestation['prestation_id'], $prestation['uniqid']);
            }
            $res .= '<button class="pointer live-click blue_button" id="finish-shop">Choisir un horaire</button>';
            echo $res;
        } else {
            echo Erra_Utils_Rest::Code_400_Bad_Request();
        }
    } else {
        echo Erra_Utils_Rest::Code_400_Bad_Request();
    }
}

/**
 * choisir_date - Selection d'une date
 */
if (isset($_POST['query']) && $_POST['query'] == 'choisir_date') {
    if (isset($_POST['rdv_data']) && is_array($_POST['rdv_data'])) {
        $res = '';

        $date = time();
        if (strlen($_POST['date']) && count(explode('-', $_POST['date'])) == 3) {
            $date = strtotime(date_euro_to_unix_format(str_replace('-', '/', $_POST['date'])));
        }
        // Obtenir les eventuelles prestations en session
        $prestations = $_POST['rdv_data'];
        $forceAgenda = (isset($_POST['force_agenda']) && is_numeric($_POST['force_agenda'])) ? $_POST['force_agenda'] : 'null';
        $res .= displayCalendar($date, $_POST['rdv_data'], $forceAgenda);
        echo $res;
    } else {
        echo Erra_Utils_Rest::Code_400_Bad_Request();
    }
}

/**
 * login_form - Formulaire de login
 */
if (isset($_POST['query']) && $_POST['query'] == 'login_form') {
    $res = '';
    $res .= '<div id="choose-mode">';
    $res .= '   <div id="login-display" class="pointer">Me connecter</div>';
    $res .= '   <div id="register-display" class="pointer">M\'inscrire</div>';
    $res .= '</div>';
    $res .= '<i>Veuillez vous connecter ou vous inscrire pour poursuivre</i><br/>';

    $res .= '<div id="login-part">';
    $res .= '   <div id="login-password">';
    $res .= '   <div id="login-form-object" class="form">';
    $res .= Erra_Fields_Text::create('login')
            ->setDescription('Adresse e-mail')
            ->edit();
    $res .= Erra_Fields_Password::create('password')
            ->setDescription('Mot de passe')
            ->edit();
    $res .= '           <span class="pointer" id="retour-mot-de-passe">Mot de passe oublié ?</span><br/>';
    $res .= '           <center><input class="erra-form-jqueryui-submit_button login-client-ajax" value="Me connecter" id="try-login" type="submit"></center>';
    $res .= '       </div>';
    $res .= '   </div>';
    $res .= '</div>';

    $res .= '<div id="password-reminder-part" style="display:none;">';
    $res .= '   <div class="form">';
    $res .= Erra_Fields_Text::create('mail_address')
            ->setDescription('Votre adresse e-mail')
            ->edit();
    $res .= '       <span class="pointer" id="retour-connexion">Retour à la connexion</span><br/>';
    $res .= '       <input class="erra-form-jqueryui-submit_button" value="Renvoyer mon mot de passe" id="send-password" type="submit">';
    $res .= '   </div>';
    $res .= '</div>';

    $res .= '<div id="register-part" style="display:none">';
    $userObject = Msa_ClientObject::getObject(uniqid(), 'CREATE', null);
    $userObject->client_internet->setValue(1);
    $res .= $userObject->ajaxFormRegister();
    $res .= '</div>';
    echo $res;
}


if ($_POST['query'] == 'get_user_profile_light') {
    if (isset($_POST['object_id'])) {
        Erra_Core_DatabasePdo::SELECT('SELECT id FROM msa_clientobject WHERE object_id="' . $_POST['object_id'] . '"');
        if (Erra_Core_DatabasePdo::rowCount()) {
            $res .= Msa_ClientObject::getObject($_POST['object_id'], 'SQL|CREATE', null)->ajaxFormEdit(true);
        } else {
            $res .= 'Aucun rendez-vous';
        }
        echo $res;
    } else {
        echo Erra_Utils_Rest::Code_304_Not_Modified('Impossible d\'afficher les rendez-vous client');
    }
}

/*
 * create_ajax_user - Création d'un utilisateur AJAX
 */
if ($_POST['query'] == 'create_ajax_user') {
    $post = array();
    foreach ($_POST['data'] as $key => $value) {
        $post[$value['name']] = $value['value'];
    }
    $password = $post['mot_de_passe'];
    $post['mot_de_passe'] = __crypt($post['mot_de_passe']);
    $post['mot_de_passe_confirm'] = __crypt($post['mot_de_passe_confirm']);

    $post['object_class'] = 'Msa_ClientObject';
    $post['object_id'] = uniqid();
    $column_names = array_keys($post);
    $column_values = ajax_sanitize_input_for_db_insert(array_values($post));
    $request = 'INSERT INTO msa_clientobject(' . implode(', ', $column_names) . ') VALUES(' . implode(',', $column_values) . ')';
    $result = Erra_Core_DatabasePdo::EXECUTE($request);
    $queryResult = Erra_Core_DatabasePdo::SELECT('SELECT id, email, nom, prenom FROM msa_clientobject WHERE object_id="' . $post['object_id'] . '"');
    if (Erra_Core_DatabasePdo::rowCount()) {
        $row = $queryResult->fetch();
        $res = Erra_Utils_Rest::Code_200_OK();
        $res .= Msa_ClientObject::getObject($post['object_id'], 'SQL', null)->ajaxFormEdit();
        echo $res;
        // Send registration mail
        if (filter_var($post['email'], FILTER_VALIDATE_EMAIL)) {
            $shopName = Config_GeneralConfigObject::get('nom_etablissement');
            $fullName = $row->nom . ' ' . $row->prenom;
            $placeHolders = array('{nom_etablissement}' => $shopName,
                '{email_client}' => $row->email,
                '{mot_de_passe_client}' => $password,
                '{nom_complet}' => $fullName);
            $result = Erra_Utils_Tools::sendTemplatedMail($post['email'], 'Mail/Mail_ClientRegister.phtml', $placeHolders);
        }
    } else {
        echo Erra_Utils_Rest::Code_304_Not_Modified('Impossible de créer la fiche client');
    }
}

/**
 * edit_ajax_user - Edition d'un utilisateur en AJAX
 */
if ($_POST['query'] == 'edit_ajax_user') {
    $post = array();
    foreach ($_POST['data'] as $key => $value) {
        $post[$value['name']] = $value['value'];
    }
    unset($post['mot_de_passe']);
    unset($post['mot_de_passe_confirm']);

    $post['object_class'] = 'Msa_ClientObject';
    $column_names = array_keys($post);
    $column_values = ajax_sanitize_input_for_db_insert(array_values($post));
    $request = 'UPDATE msa_clientobject SET ';
    foreach ($column_names as $key => $column_name) {
        $request .= $column_name.='=' . $column_values[$key];
        if ($key <= (count($column_names) - 2)) {
            $request .= ', ';
        }
    }
    $request .= ' WHERE object_id="' . $post['object_id'] . '"';
    $result = Erra_Core_DatabasePdo::EXECUTE($request);
    if (Erra_Core_DatabasePdo::rowCount()) {
        echo Erra_Utils_Rest::Code_200_OK('Profil mis à jour avec succès');
    } else {
        echo Erra_Utils_Rest::Code_304_Not_Modified('Impossible de créer la fiche client');
    }
}

/**
 * login_user - Login d'un utilisateur
 */
if ($_POST['query'] == 'login_user') {
    $post = $_POST;
    if (isset($_POST['login']) && strlen($_POST['login']) && isset($_POST['password']) && strlen($_POST['password'])) {
        // Check if email exists
        $password = __crypt($_POST['password']);
        $result = Erra_Core_DatabasePdo::SELECT('SELECT * FROM msa_clientobject WHERE email="' . $_POST['login'] . '" AND mot_de_passe="' . $password . '"');
        if (Erra_Core_DatabasePdo::rowCount()) {
            $row = $result->fetch();
            echo Erra_Utils_Rest::Code_200_OK();
            echo Msa_ClientObject::getObject($row->object_id, 'SQL', null)->ajaxFormEdit();
        } else {
            echo Erra_Utils_Rest::Code_404_Not_Found('Mauvais nom d\'utilisateur ou mot de passe');
        }
    } else {
        echo Erra_Utils_Rest::Code_400_Bad_Request("Erreur dans la requête");
    }
}

/**
 * check_ajax_user - Vérifie si l'email de l'utilisateur existe ou non
 */
if ($_POST['query'] == 'check_ajax_user') {
    $post = $_POST;
    if (isset($post['email']) && strlen($post['email'])) {
// Check if email exists
        Erra_Core_DatabasePdo::SELECT('SELECT id FROM msa_clientobject WHERE email="' . $post['email'] . '"');
        if (Erra_Core_DatabasePdo::rowCount()) {
            echo Erra_Utils_Rest::Code_306_Reserved();
        } else {
            echo Erra_Utils_Rest::Code_200_OK();
        }
    }
}

/**
 * send_password - Envoi du mot de passe
 */
if ($_POST['query'] == 'send_password') {
    if (isset($_POST['mail_address']) && filter_var($_POST['mail_address'], FILTER_VALIDATE_EMAIL)) {
        $result = Erra_Core_DatabasePdo::SELECT('SELECT id, nom, prenom, mot_de_passe, email FROM msa_clientobject WHERE email="' . $_POST['mail_address'] . '"');
        if (Erra_Core_DatabasePdo::rowCount()) {
            $row = $result->fetch();
            $mail = $_POST['mail_address'];
            $password = __decrypt($row->mot_de_passe);
            $fullName = $row->nom . ' ' . $row->prenom;
            $shopName = Config_GeneralConfigObject::get('nom_etablissement');
            $placeHolders = array('{nom_etablissement}' => $shopName, '{email_client}' => $row->email, '{mot_de_passe_client}' => $password, '{nom_complet}' => $fullName);
            $result = Erra_Utils_Tools::sendTemplatedMail($_POST['mail_address'], 'Mail/Mail_ClientPasswordForgot.phtml', $placeHolders);
            echo Erra_Utils_Rest::Code_200_OK('Un mail contenant vos identifiants a été envoyé ');
        } else {
            echo Erra_Utils_Rest::Code_406_Not_Acceptable("Cette adresse n'est pas enregistrée dans notre base ");
        }
    } else {
        echo Erra_Utils_Rest::Code_400_Bad_Request("Mauvais requête ");
    }
}

/**
 * get_user_profile - Retourne le profil de l'utilisateur
 */
if ($_POST['query'] == 'get_user_profile') {
    if (isset($_POST['object_id'])) {
        Erra_Core_DatabasePdo::SELECT('SELECT id FROM msa_clientobject WHERE object_id="' . $_POST['object_id'] . '"');
        if (Erra_Core_DatabasePdo::rowCount()) {
            $res .= Msa_ClientObject::getObject($_POST['object_id'], 'SQL|CREATE', null)->ajaxFormEdit();
        } else {
            $res .= 'Impossible d\'afficher la fiche client';
        }
        echo $res;
    } else {
        echo Erra_Utils_Rest::Code_304_Not_Modified('Impossible d\'afficher la fiche client');
    }
}

/**
 * get_user_header - Retourne le header de l'utilisateur
 */
if ($_POST['query'] == 'get_user_header') {
    if (isset($_POST['object_id'])) {
        $user = Erra_Core_DatabasePdo::SELECT('SELECT nom, prenom FROM msa_clientobject WHERE object_id="' . $_POST['object_id'] . '"');
        if (Erra_Core_DatabasePdo::rowCount()) {
            $row = $user->fetch();
            $res .= '<a href="#profil">';
            $res .= 'Bienvenue ' . ucfirst($row->nom) . ' ' . ucfirst($row->prenom);
            $res .= '</a>';
            $res .= '<div class="pointer disconnect">Déconnexion</div>';
        }
        echo $res;
    } else {
        echo Erra_Utils_Rest::Code_304_Not_Modified('Impossible d\'afficher la fiche client');
    }
}

/**
 * book_rdv - Booking du RDV
 */
if (isset($_POST['query']) && $_POST['query'] == 'book_rdv') {
    if (isset($_POST['rdv_data']) && is_array($_POST['rdv_data'])) {
        $prestaMailList = array();
        $prestations = $_POST['rdv_data'];
        $extra_fields = $_POST['extra_fields'];
        $heure_reservation = '';
        if (is_array($prestations) && count($prestations)) {
            $prestationChainDelay = 0;
            $prestationStr = '';
            foreach ($prestations as $prestation) {
                $data = array();
                $data['object_class'] = 'Msa_SlotObject';
                $data['object_id'] = $prestation['uniqid'];
                $data['event_id'] = $prestation['uniqid'];
                $data['agenda_id'] = $_POST['agenda_id'];
                if (strstr($_POST['agenda_id'], '-')) {
                    $agendaList = filter_array(explode('-', $_POST['agenda_id']));
                    $selectableAgendas = array();
                    foreach ($agendaList as $agenda) {
                        if (is_numeric($agenda) && $agenda > 0) {
                            $selectableAgendas[] = $agenda;
                        }
                    }
                    if (count($selectableAgendas)) {
                        $randomIndex = rand(0, count($selectableAgendas) - 1);
                        $data['agenda_id'] = $selectableAgendas[$randomIndex];
                    }
                } else if (is_numeric($_POST['agenda_id'])) {
                    $data['agenda_id'] = $_POST['agenda_id'];
                }

                $data['event_type'] = 'presta';
                $data['prestation_id'] = $prestation['prestation_id'];
                for ($i = 1; $i <= 5; $i++) {
                    if (isset($_POST['extra_field_' . $i])) {
                        $data['extra_field_' . $i] = $_POST['extra_field_' . $i];
                    }
                }
                $data['slot_day'] = strtotime(date('m/d/Y', $_POST['realStart']));
                $data['slot_start'] = $_POST['realStart'] - $data['slot_day'] + $prestationChainDelay;
                if (!strlen($heure_reservation)) {
                    $heure_reservation = time_to_str_hour($data['slot_start']);
                }
                $data['slot_end'] = 1; // For a prestation it's computed dynamically anyway
                $data['status_rdv'] = 'en_attente';
                $data['client_id'] = $_POST['client_id'];
                $clientDBLine = Erra_Core_DatabasePdo::SELECT('SELECT id, nom, prenom, email, telephone_portable FROM msa_clientobject WHERE object_id="' . $data['client_id'] . '"')->fetch();
                $data['client_id'] = $clientDBLine->id;
                if (is_array($extra_fields) && count($extra_fields)) {
                    foreach ($extra_fields as $key => $extra_value) {
                        $data[$key] = $extra_value;
                    }
                }
                $data['from_internet'] = 1;
                $data['date_commande'] = time();
                $data['last_sync'] = time();
                $column_names = array_keys($data);
                $column_values = ajax_sanitize_input_for_db_insert(array_values($data));
                $request = 'INSERT INTO msa_slotobject(' . implode(', ', $column_names) . ') VALUES(' . implode(',', $column_values) . ')';
                $result = Erra_Core_DatabasePdo::EXECUTE($request);

                Tools_GCalendarObject::deleteEventFromUniqid($prestation['uniqid']);
                Tools_GCalendarObject::addEventFromUniqId($prestation['uniqid']);

                // Fetch data for sql
                $queryDB = Erra_Core_DatabasePdo::SELECT('SELECT id, internet_name, prestation_name, duree, prix FROM msa_prestationobject WHERE id =' . $data['prestation_id'])->fetch();
                $presta_name = strlen($queryDB->internet_name) ? $queryDB->internet_name : $queryDB->prestation_name;
                $prestationStr .= '<strong>' . $presta_name . '</strong> à ' . time_to_str_hour($data['slot_start']) . ' (' . minutes_to_str_hour($queryDB->duree) . ', ' . $queryDB->prix . '€)<br/>';

                $prestationChainDelay += $queryDB->duree * 60;

                // Add infos for prestas
                ////////////////////////
                // Add prestation list and client infos
                if (!isset($prestaMailList[$data['agenda_id']])) {
                    $prestaMailList[$data['agenda_id']] = array();
                }
                $prestaMailList[$data['agenda_id']][] = array('client_id' => $_POST['client_id'], 'prestation_id' => $prestation['prestation_id'], 'slot_day' => $data['slot_day'], 'slot_start' => $data['slot_start']);
            }
            // Confirmation du ou des rendez-vous
            // /////////////////////////////////
            $nom_complet = $clientDBLine->nom . ' ' . $clientDBLine->prenom;
            $nom_etablissement = Config_GeneralConfigObject::get('nom_etablissement');
            $nom_prestation = $prestationStr;
            $date_reservation = date('d/m/Y', $_POST['realStart']);

            $placeHolders = array('{nom_complet}' => $nom_complet,
                '{nom_etablissement}' => $nom_etablissement,
                '{nom_prestation}' => $nom_prestation,
                '{date_reservation}' => $date_reservation,
                '{heure_reservation}' => $heure_reservation);
            // Client Side
            //////////////
            $result = Erra_Utils_Tools::sendTemplatedMail($clientDBLine->email, 'Mail/Mail_RdvConfirmUser.phtml', $placeHolders);
            if (Config_GeneralConfigObject::get('sms_client_newrdv') == 1) {
                $result = Erra_Utils_Tools::sendTemplatedSms($clientDBLine->telephone_portable, 'Sms/Sms_RdvConfirmUser.phtml', $placeHolders);
            }
            // Presta Side
            //////////////
            if (count($prestaMailList)) {
                foreach ($prestaMailList as $agenda_id => $rdvDataList) {
                    if (is_array($rdvDataList) && count($rdvDataList)) {
                        foreach ($rdvDataList as $rdvData) {
                            $prestaQuery = Erra_Core_DatabasePdo::SELECT('SELECT msa_agendaobject.email AS presta_email, msa_agendaobject.telephone_portable AS presta_portable, nom, prenom, prestation_name FROM msa_agendaobject, msa_clientobject, msa_prestationobject WHERE msa_agendaobject.id=' . $agenda_id . ' AND msa_clientobject.object_id="' . $rdvData['client_id'] . '" AND msa_prestationobject.id=' . $rdvData['prestation_id']);
                            if (is_object($prestaQuery)) {
                                $prestaQuery = $prestaQuery->fetch();
                                $placeHolders = array('{nom_client}' => $prestaQuery->nom . ' ' . $prestaQuery->prenom,
                                    '{nom_etablissement}' => $nom_etablissement,
                                    '{nom_prestation}' => $prestaQuery->prestation_name,
                                    '{date_reservation}' => date('d/m/Y', $rdvData['slot_day']),
                                    '{heure_reservation}' => time_to_str_hour($rdvData['slot_start']));

                                if (Config_GeneralConfigObject::get('mail_team_newrdv') == 1) {
                                    $result = Erra_Utils_Tools::sendTemplatedMail($prestaQuery->presta_email, 'Mail/Mail_RdvConfirmPresta.phtml', $placeHolders);
                                }
                                if (Config_GeneralConfigObject::get('sms_team_newrdv') == 1) {
                                    $result = Erra_Utils_Tools::sendTemplatedSms($prestaQuery->presta_portable, 'Sms/Sms_RdvConfirmPresta.phtml', $placeHolders);
                                }
                            }
                        }
                    }
                }
            }
            // Get redirection URL if exists
            $finalContent = Erra_Core_DatabasePdo::SELECT('SELECT redirection_url, promo_content FROM msa_locationobject WHERE id = (SELECT location FROM msa_agendaobject WHERE id=' . $data['agenda_id'] . ')');
            $redirection_url = '';
            $promo_content = '';
            if (Erra_Core_DatabasePdo::rowCount()) {
                $finalContent = $finalContent->fetch();
                $redirection_url = $finalContent->redirection_url;
                if (strlen($finalContent->promo_content)) {
                    $promo_content = '<br/><br/>' . $finalContent->promo_content;
                }
            }
            $redirection_url = (strlen($redirection_url) && strstr($redirection_url, 'http')) ? $redirection_url : Config_GeneralConfigObject::get('url_reservation');
            // Fin
            echo Erra_Utils_Rest::Code_200_OK('Votre rendez-vous a été enregistré, vous allez recevoir un e-mail de confirmation ' . $promo_content . ' ' . $redirection_url . ' ');
        } else {
            echo Erra_Utils_Rest::Code_400_Bad_Request("Erreur dans la requête");
        }
    } else {
        echo Erra_Utils_Rest::Code_400_Bad_Request("Erreur dans la requête");
    }
}

/**
 * final_rdv_dialog - Finalisation du rendez-vous
 */
if (isset($_POST['query']) && $_POST['query'] == 'final_rdv_dialog') {
    if (isset($_POST['rdv_data']) && is_array($_POST['rdv_data']) && is_numeric($_POST['date_selected'])) {
        $res = Erra_Utils_Rest::Code_200_OK();
        $dayListFr = array(0 => 'Lundi', 1 => 'Mardi', 2 => 'Mercredi', 3 => 'Jeudi', 4 => 'Vendredi', 5 => 'Samedi', 6 => 'Dimanche');
        $monthListFr = array(1 => 'Jan', 2 => 'Fév', 3 => 'Mar', 4 => 'Avr', 5 => 'Mai', 6 => 'Juin', 7 => 'Juil', 8 => 'Août', 9 => 'Sept', 10 => 'Oct', 11 => 'Nov', 12 => 'Déc');

        // Date choisie
        $date_selected = $_POST['date_selected'];

        $res .= 'Rendez-pris le ' . date('d', $date_selected) . ' ' . $monthListFr[date('n', $date_selected)] . ' ' . date('Y', $date_selected);
        $res .= ' à ' . date('G', $date_selected) . 'h' . date('i', $date_selected);

        $prestations = $_POST['rdv_data'];
        $shop_id = $prestations[0]['shop_id'];
        $prestation_id_list = array();
        foreach ($prestations as $prestation) {
            $prestation_id_list[] = $prestation['prestation_id'];
        }
        // Display available agendas
        $realAgendas = array_unique(filter_array(explode(';', $_POST['match_agendas'])));
        $query = 'SELECT nom_agenda, nom_internet, id FROM msa_agendaobject WHERE id IN(' . implode(',', $realAgendas) . ');';
        $selectedAgendas = Erra_Core_DatabasePdo::SELECT($query);
        if (Erra_Core_DatabasePdo::rowCount()) {
            $agendaList = array(implode('-', $realAgendas) => 'Peu importe');
            while ($row = $selectedAgendas->fetch()) {
                $agendaList[$row->id] = strlen($row->nom_internet) ? $row->nom_internet : $row->nom_agenda;
            }

            // TODO IF CONFIG IS NOT OK, PUT THIS HAS AN HIDDEN FIELD
            $res .= Erra_Fields_ComboBox::create('selected_agenda')
                    ->setDescription('Choisir un agenda')
                    ->fill($agendaList)
                    ->edit();
        }
        // Display prestations list
        if (is_array($prestations) && count($prestations)) {
            foreach ($prestations as $prestation) {
                $res .= displaySmallPrestationFromId($prestation['prestation_id'], $prestation['uniqid'], false);
            }

            // Display extra fields
            $res .= Msa_ExtraPrestationFieldObject::echoExtraFields();
            echo $res;
        } else {
            echo Erra_Utils_Rest::Code_400_Bad_Request();
        }
    } else {
        echo Erra_Utils_Rest::Code_400_Bad_Request();
    }
}

/**
 * 26/03/2013 Par Jian LI
 * update_object - Mise à jour d'un objetn les paramètres sont passées par method Post
 * Retourner un objet JSON
 * Champs requis:
 *      obejct: Le nom de la table
 *      update: Une list de nouvelle valeur
 *      id: id d'objet à modifier
 */
if (isset($_POST['query']) && $_POST['query'] == 'update_object') {
    $ajax_result = array();
    
    if(isset($_POST['object'])){
        $query = "UPDATE ".$_POST['object'].' SET ';
        foreach($_POST['update'] as $champ=>$new_val){
            $query .= $champ."='$new_val'";
        }
        $query .= " Where id=".$_POST['id'];
    }
    $return_val = Erra_Core_DatabasePdo::EXECUTE($query);
    $ajax_result['query'] = $query;
    
    if($return_val !== FALSE){
        $ajax_result['result'] = 'Success';
    }else{
        $ajax_result['result'] = 'Failed';
    }
    echo json_encode($ajax_result);
}